package com.maddox.relax.view.sub;

import android.app.ActionBar;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.maddox.relax.R;
import com.maddox.relax.model.DataModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 流式布局多选版本用
 *
 * @author Maddox
 */
public class MSelectFlowLayout extends ViewGroup {
    private Context mContext;
    private int textColor = Color.WHITE;//默认展示的文本颜色
    private Drawable textDrawable;//展示的文本背景色

    //记录所有行的View列表
    private List<List<View>> mViews = new ArrayList<>();
    //记录所有行的各自最大高度
    private List<Integer> mLineHeight = new ArrayList<>();
    //记录当前绘制的实体数据
    private List<DataModel> itemList = new ArrayList<>();
    private int textIcon;//文本右侧小图片


    public MSelectFlowLayout(Context context) {
        this(context, null);
    }

    public MSelectFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MSelectFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;

    }


    public String removeItem(int position) {
        String name = itemList.get(position).getText();
        itemList.remove(position);
        List<DataModel> newList = new ArrayList<>();
        newList.addAll(itemList);
        setData(newList);
        return name;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //当前布局的最大宽度和高度
        int width = 0;
        int height = 0;
        //每一行子view的宽高
        int lineWidth = 0;
        int lineHeight = 0;
        int count = getChildCount();

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == GONE) {
                continue;
            }
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //获取每个子View的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //获取每个子View的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            //如果当前子View与当前行的已使用宽度超出了父布局的宽度大小,则进入下一行
            if (lineWidth + childWidth > widthSize - getPaddingLeft() - getPaddingRight()) {
                //超出一行,先记录当前行的宽度,再去新建一行
                width = Math.max(width, lineWidth);
                //新的一行宽度等于当前子View的宽度
                lineWidth = childWidth;
                //记录行总高度
                height += lineHeight;
                //记录新一行的高度
                lineHeight = childHeight;
            } else {
                //如果没有换行,则累加当前子View的宽度到当前行宽度
                lineWidth += childWidth;
                //得到行子View的最大行高度
                lineHeight = Math.max(lineHeight, childHeight);
            }
            //处理最后一个子View的情况
            if (i == count - 1) {
                width = Math.max(lineWidth, width);
                height += lineHeight;
            }

        }
        //当父布局的宽高为具体值时,就使用设置的具体值,否则使用子View的总体宽高
        int resultW = widthMode == MeasureSpec.EXACTLY ? widthSize : width + getPaddingLeft() + getPaddingRight();
        int resultH = heightMode == MeasureSpec.EXACTLY ? heightSize : height + getPaddingTop() + getPaddingBottom();
        //设置父布局的大小
        setMeasuredDimension(resultW, resultH);


    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mViews.clear();
        mLineHeight.clear();
        //获取当前ViewGroup的宽度
        int width = getWidth();
        int lineWidth = 0;
        int lingHeight = 0;
        //记录当前行的View
        List<View> lineViews = new ArrayList<>();
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width - getPaddingLeft() - getPaddingRight()) {
                mLineHeight.add(lingHeight);
                mViews.add(lineViews);
                lineWidth = 0;
                lingHeight = childHeight + lp.topMargin + lp.bottomMargin;
                lineViews = new ArrayList<>();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lingHeight = Math.max(lingHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        //记录每行高度,为后面设置子View单独top做准备,比如 gravity
        mLineHeight.add(lingHeight);
        mViews.add(lineViews);

        int left = getPaddingLeft();
        int top = getPaddingTop();
        int lineCount = mViews.size();
        for (int i = 0; i < lineCount; i++) {
            lineViews = mViews.get(i);
            lingHeight = mLineHeight.get(i);
            int lineViewCount = lineViews.size();

            for (int j = 0; j < lineViewCount; j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = child.getMeasuredWidth() + cLeft;
                int cBottom = cTop + child.getMeasuredHeight();
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;


            }

            left = 0;
            top += lingHeight;
        }
    }

    /**
     * 设置填充数据
     *
     * @param data
     */
    public void setData(List<DataModel> data) {
        removeAllViews();
        if (data == null || data.size() <= 0) {
            return;
        }
        itemList.clear();
        itemList.addAll(data);
        MarginLayoutParams lp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 5;
        lp.rightMargin = 5;
        lp.topMargin = 5;
        lp.bottomMargin = 5;
        //初始化布局加载器
        for (int i = 0; i < data.size(); i++) {
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.layout_flow_item, null, false);
            TextView itemText = itemView.findViewById(R.id.tv_item_name);
            ImageView itemIcon = itemView.findViewById(R.id.iv_item_icon);
            itemText.setText(data.get(i).getText());
            itemText.setTextColor(textColor);
            if (textDrawable != null) {
                itemView.setBackground(textDrawable);
            }
            if (textIcon != 0) {
                itemIcon.setImageResource(textIcon);
            }
            addView(itemView, lp);
        }
        //因为是新创建的View,需要重新加载监听器
        if (clickListener != null) {
            setOnItemClickListener(clickListener);
        }
    }

    private int randomColor() {
        Random random = new Random();
        return Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }

    private OnItemClickListener clickListener;

    /**
     * 设置点击事件
     *
     * @param clickListener 点击回调
     */
    public void setOnItemClickListener(OnItemClickListener clickListener) {
        if (clickListener == null)
            return;
        this.clickListener = clickListener;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int index = i;
            child.setOnClickListener(v -> {
                this.clickListener.onItemClick(child, index);
            });
        }


    }

    public List<DataModel> getItemList() {
        return itemList;
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    public void setItemTextColor(int color) {
        textColor = color;
    }

    public void setItemBackgroundDrawable(Drawable drawable) {
        textDrawable = drawable;
    }

    public void setItemTextIcon(int imgRes) {
        textIcon = imgRes;
    }


    public static interface OnItemClickListener {
        void onItemClick(View itemView, int position);
    }

}
